package com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzxczh.constants.FxfzConstants;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.repository.SamPoiDataRepository;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.entity.InvestigationPersonnel;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.entity.InvestigationTeam;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.repository.InvestigationGroupRepository;
import com.css.fxfzxczh.modules.fieldWorkManage.lnvestigationTaskMange.entity.InvestigationTask;
import com.css.fxfzxczh.modules.fieldWorkManage.lnvestigationTaskMange.repository.InvTaskManageRepository;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.entity.SurTaskManage;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.repository.SurTaskManageRepository;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.service.SurTaskManageService;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.vo.SurTaskManageVo;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.vo.UpdateVO;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.repository.EarEveManageRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.service.EarEveManageService;
import com.css.fxfzxczh.util.CreateGson;
import com.css.fxfzxczh.util.PlatformObjectUtils;
import com.css.fxfzxczh.util.RedisLockUtil;
import com.css.fxfzxczh.util.UUIDGenerator;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import com.css.fxfzxczh.zcpt.sys.service.SysRoleService;
import com.css.fxfzxczh.zcpt.sys.service.impl.SUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SurTaskManageServiceImpl implements SurTaskManageService {

    @Resource
    SurTaskManageRepository surTaskManageRepository;

    @Autowired
    SUserServiceImpl sUserServiceImpl;

    @Resource
    private RedisLockUtil redisLockUtil;

    @Resource
    SUserService sUserService;

    @Resource
    InvestigationGroupRepository investigationGroupRepository;

    @Resource
    EarEveManageRepository earEveManageRepository;

    @Resource
    EarEveManageService earEveManageService;

    @Resource
    SamPoiDataRepository samPoiDataRepository;

    @Resource
    InvTaskManageRepository invTaskManageRepository;


    @Override
    public Map<String, Object> getPage(int curPage, int pageSize,String xsemId,String type) {
        Map<String, Object> page = surTaskManageRepository.getPage(curPage, pageSize,xsemId,type);
        return page;
    }



    @Override
    @Transactional(rollbackFor = Exception.class )
    public void save(SurTaskManageVo surTaskManageVo) {
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        String userID = PlatformSessionContext.getUserID();
        String uuid = UUIDGenerator.getUUID();
        surTaskManageVo.setXstmId(uuid);
        surTaskManageVo.setDelFlag(YNEnum.N.toString());
        surTaskManageVo.setIsRelation(YNEnum.N.toString());
        surTaskManageVo.setTaskStatus("0");
        surTaskManageVo.setUpdateFlag("1");
        surTaskManageVo.setXsemId(currentEvent.getXsemId());
        surTaskManageVo.setXsemCode(currentEvent.getEventCode());
        SurTaskManage surTaskManage=new SurTaskManage();
        BeanUtils.copyProperties(surTaskManageVo, surTaskManage);
        List<String> xspdIdList = surTaskManageVo.getXspdIdList();
        if(PlatformObjectUtils.isNotEmpty(xspdIdList)){
            samPoiDataRepository.associatedSubarea(xspdIdList,uuid);
        }
        surTaskManageRepository.save(surTaskManage);
    }

    @Override
    public void update(SurTaskManage surTaskManage) {
        // String userId = PlatformSessionContext.getUserID();
//        String role = sysRoleService.getRoleByUserId(userId);
//        StringBuilder str = new StringBuilder("");
//        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
//        for (Map roleMap : roleMaps) {
//            str.append(roleMap.get("roleCode") + ",");
//        }
//        String roles = str.toString();
        surTaskManage.setUpdateTime(new Date());
        surTaskManage.setUpdateUser(PlatformSessionContext.getUserID());
        surTaskManage.setUpdateFlag("1");
        //if (roles.contains(FxfzConstants.YPG_COUN_GL_ROLE) || roles.contains(FxfzConstants.YPG_PRI_GL_ROLE)) {
        surTaskManageRepository.update(surTaskManage);
        //}else{
        //  throw new RuntimeException("修改失败，当前用户不是省级管理员或国家级管理员");
        //}

    }

    @Override
    public SurTaskManage findById(String id) {
        return surTaskManageRepository.findById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String ids) {
        String[] split = ids.split(",");
        for(String id:split){
            SurTaskManage surTaskManage = this.findById(id);
            if(!"1".equals(surTaskManage.getIsRelation())){
                surTaskManageRepository.delete(id);
                samPoiDataRepository.updateAssociationbyXstmId(id);
            }else {
                throw new RuntimeException("删除失败，当前调查任务已被关联");
            }
        }
    }

    @Override
    public Map<String, Object> getCode(String eventCode) {
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        eventCode=currentEvent.getEventCode();
        Map<String, Object> map=new HashMap<>();
        //StringBuilder taskCode = new StringBuilder(eventCode+"DCRW");
        StringBuilder evaSubCode = new StringBuilder(eventCode+"PGZQ");



        //map.put("taskCode",getCodeFun(taskCode, "0"));
        map.put("evaluationSubareaCode",getCodeFun(evaSubCode, "1"));
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        map.put("createUserName", sUser.getUserName());
        map.put("createUser", sUser.getUserId());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("createTime", dateFormat.format(new Date()));
        //map.put("createUnit", sUser.getDeptEntity().getDeptName());
        map.put("createUnit", sUser.getOrgName());
        return map;
    }

    @Override
    public List<SurTaskManage> getTaskListByXsemId(String xsemId) {
        return surTaskManageRepository.getTaskListByXsemId(xsemId);

    }

    @Override
    public Map<String, Object> getTaskListByXsemIdAndType(String xsemId,String type,int curPage,int pageSize) {
        return surTaskManageRepository.getTaskListByXsemIdAndType(xsemId,type,curPage,pageSize);
    }

    @Override
    public List<SurTaskManage> getAllData(String xsemId,String type) {
        return surTaskManageRepository.getAllData(xsemId,type);
    }

    @Override
    public void updateTaskStatu(UpdateVO updateVO) {
        /*EarEveManage currentEvent = earEveManageRepository.getCurrentEvent(updateVO.getUserId());
        List<InvestigationTeam> list=investigationGroupRepository.findByLeaderId(updateVO.getUserId(),currentEvent.getXsemId());
        if(list.size()>0){
            surTaskManageRepository.updateTaskStatu(updateVO.getXstmId(),updateVO.getTaskStatus());
        }else{
            throw new RuntimeException("当前登录账号不是组长账号");
        }*/
        SurTaskManage surTaskManage = surTaskManageRepository.findById(updateVO.getXstmId());
        String groupId = surTaskManage.getGroupId();
        if(PlatformObjectUtils.isNotEmpty(groupId)){
            InvestigationTeam group = investigationGroupRepository.findById(groupId);
            if(updateVO.getUserId().equals(group.getLeaderId())){
                surTaskManageRepository.updateTaskStatu(updateVO.getXstmId(),updateVO.getTaskStatus());
            }else{
                throw new RuntimeException("当前登录账号不是该任务所承担小组的组长账号");
            }
        }else{
            throw new RuntimeException("该任务尚未分配小组，无法开始任务");
        }
    }

    @Override
    public List<String> getXstmIdsBYXsemId(String xsemId) {
        return surTaskManageRepository.getXstmIdsBYXsemId(xsemId);
    }

    @Override
    public List<SurTaskManage> getTaskByTypeAndXsemId(String xsemId) {

        return surTaskManageRepository.getTaskByTypeAndXsemId(xsemId);
    }

    @Override
    public Map<String, Object> getAppPage(int curPage, int pageSize, String xsemId,String userId) {
        List<String> groupIds = getRelatedGroupIds(userId, xsemId);
        Map<String, Object> page = surTaskManageRepository.getAppPage(curPage, pageSize,xsemId);
        List<SurTaskManageVo> rows = (List<SurTaskManageVo>) page.get("rows");
        for(SurTaskManageVo row:rows){
            if(groupIds.contains(row.getGroupId())){
                row.setIdentifying("0");
            }else{
                row.setIdentifying("1");
            }
        }
        return page;
    }


    private List<String> getRelatedGroupIds(String userId, String xsemId) {
        List<String> groupIdList=new ArrayList<>();
        List<InvestigationTeam> leaderList = investigationGroupRepository.findByLeaderId(userId,xsemId);
        if(leaderList.size()>0){
            for(InvestigationTeam investigationTeam:leaderList){
                groupIdList.add(investigationTeam.getXitId());
            }
            List<InvestigationPersonnel> personnelList=investigationGroupRepository.findByPersonnelId(userId,xsemId);
            if(personnelList.size()>0){
                for(InvestigationPersonnel investigationPersonnel:personnelList){
                    groupIdList.add(investigationPersonnel.getInvestigationId());
                }
            }
        }else{
            List<InvestigationPersonnel> personnelList=investigationGroupRepository.findByPersonnelId(userId,xsemId);
            if(personnelList.size()>0){
                for(InvestigationPersonnel investigationPersonnel:personnelList){
                    groupIdList.add(investigationPersonnel.getInvestigationId());
                }
            }
        }
        return groupIdList.stream().distinct().collect(Collectors.toList());
    }


    private String getCodeFun(StringBuilder code, String sign) {
        /*DecimalFormat decimalFormat=new DecimalFormat("000");
        String num="";
        String maxCode="";
        if ("0".equals(sign)) {
            maxCode = surTaskManageRepository.getMaxTaskCode(code.toString());
        } else {
            maxCode = surTaskManageRepository.getMaxEvaSubCode(code.toString());
        }

        if (PlatformObjectUtils.isEmpty(maxCode)) {
            int i = 1;
            num = decimalFormat.format(i);
        } else {
            String substring = maxCode.substring(maxCode.length() - 3);
            num = decimalFormat.format(Integer.parseInt(substring) + 1);
        }
        return code.append(num).toString();*/

        DecimalFormat decimalFormat=new DecimalFormat("000");
        String num="";
        String maxCode="";

        String requestId = UUIDGenerator.getUUID();
        Boolean isLocked = redisLockUtil.lock("redis_eventCode_lock_serialNum", requestId, 3L);
        if (isLocked) {
            if ("0".equals(sign)) {
                maxCode = surTaskManageRepository.getMaxTaskCode(code.toString());
            } else {
                maxCode = surTaskManageRepository.getMaxEvaSubCode(code.toString());
            }

            if (PlatformObjectUtils.isEmpty(maxCode)) {
                int i = 1;
                num = decimalFormat.format(i);
            } else {
                String substring = maxCode.substring(maxCode.length() - 3);
                num = decimalFormat.format(Integer.parseInt(substring) + 1);
            }
            redisLockUtil.releaseLock("redis_distributed_lock_serialNum", requestId);
        }else {
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return code.append(num).toString();
    }


}
